Command-line interface: Why?

Command line interface

Why do we want to learn how to use the command-line interface (CLI)?

Here is a great example by Doug McIlroy (Full story: http://www.leancrew.com/all-this/2011/12/more-shell-less-egg/):

$ tr -sc 'A-Za-z' '\n' < sh.txt | tr A-Z a-z | \
sort | uniq -c | sort -n -r | sed ${1}q

This counts the frequency of every word in sh.txt and shows them in descending order, without doing any “programming”. What happens here is multiple tools are composed or chained together to process the data step-by-step.

First, it uses &lt; to pass the content of a file sh.txt to a CLI tool tr, which replaces (translates) all characters that do not belong to the English alphabet (A-Za-z) with a new line character \n. Then the result gets passed to another tr script through a pipe, |. Now the tr translates uppercase characters into lowercase. Next, the result gets processed by sort. it simply sorts every line of the input. Although you can sort in many ways, without any parameters, it will sort in alphabetical order. The result is passed again to the next command, which is uniq. With -c option, it removes duplicated lines while adding the count of duplicated lines in the file. Then we are using this again using the sort command, this time with -n -r option to sort it based on the count (-n), in descending order (-r).

The later part of this script is very frequently used: https://twitter.com/mat_kelcey/status/1373752933871800322

Here is another example: https://twitter.com/raymondh/status/1358120906258673665

$ echo 'aaaabbbcca' | fold -w 1 | uniq -c

What these examples demonstrate is the Unix philosophy.

  • “Write programs that do one thing and do it well.”
  • “Write programs to work together.”
  • “Write programs to handle text streams, because that is a universal interface.”

The CLI is built on these principles. That means there are a whole bunch of useful, well-crafted tools that can be easily composed together to do more complex jobs.